const moment = require('moment')
const mongoose = require('mongoose')
const User = mongoose.model('User')
const mp = require('../../wechat')

exports.checkPassword = async (name, password) => {
  let match = false
  const user = await User.findOne({ name })

  if (user) {
    match = await user.comparePassword(password, user.password)
  }

  return match
}

exports.saveWechatUser = async (message, from = '') => {
  let sceneId = message.EventKey
  let ticket = message.ticket
  let openid = message.FromUserName
  let count

  if (sceneId && sceneId.indexOf('qrscene_') > -1) {
    sceneId = sceneId.replace('qrscene_', '')
  }

  if (sceneId === 'imooc') {
    from = 'imooc'
  }

  let user = await User.findOne({
    'wechat.openid': openid
  })

  const client = mp.getWechat()
  const tokenData = await client.fetchAccessToken()
  let wxUser = await client.handle('getUserInfo', message.FromUserName, tokenData.access_token)

  if (!user || !user._id || !user.wechat) {
    let nickname = wxUser.nickname || wxUser.openid
    let userData = {
      role: 0,
      name: nickname + '_' + Date.now(),
      wechat: {
        sex: 1,
        from: from,
        avatar: wxUser.headimgurl,
        subscribe: 1,
        openid: wxUser.openid,
        nickname: nickname,
        language: wxUser.language,
        city: wxUser.city,
        province: wxUser.province,
        country: wxUser.country,
        subscribe_time: moment(wxUser.subscribe_time).format()
      }
    }
    // 扫描关注
    if (sceneId) {
      userData.wechat.sceneId = sceneId
      userData.wechat.ticket = ticket
    }

    user = new User(userData)
  } else {
    user.wechat = {
      from: from,
      subscribe: 1,
      openid: wxUser.openid,
      nickname: wxUser.nickname,
      avatar: wxUser.headimgurl,
      sex: 1,
      language: wxUser.language,
      city: wxUser.city,
      province: wxUser.province,
      country: wxUser.country,
      subscribe_time: moment(wxUser.subscribe_time).format()
    }

    // 扫描关注
    if (sceneId) {
      user.wechat.sceneId = sceneId
      user.wechat.ticket = ticket
    }

    user.markModified('wechat')
  }

  if (from === 'imooc') {
    let tagsData

    // 获取公众号已创建的标签列表
    try {
      tagsData = await client.handle('fetchTags', tokenData.access_token)
    } catch (e) {
      console.log('获取分组信息失败')
    }

    // {tags: [
    //   { id: 0, name: '未分组', count: 970 },
    //   { id: 1, name: '黑名单', count: 0 },
    //   { id: 2, name: '星标组', count: 0 },
    //   { id: 102, name: 'testimooc', count: 0}
    // ]}
    tagsData = tagsData || {}

    let tags = tagsData.tags || []
    let tag = tags.filter(tag => {
      return tag.name === 'testimooc'
    })
    let tagid

    count = await User.count({
      'wechat.from': 'imooc'
    })
    if (tag && tag.length > 0) {
      tagid = parseInt(tag[0].id, 10)
      count = count || tag[0].count || 0
    } else {
      // 创建分组
      try {
        let res = await client.handle('createTag', tokenData.access_token, 'testimooc')

        console.log(res)
        tagid = parseInt(res.tag.id, 10)
      } catch (err) {
        console.log('创建分组失败')
        console.log(err)
      }
    }

    if (tagid) {
      // 移动到分组
      try {
        let msg = await client.handle('batchTag', [openid], tokenData.access_token)

        if (msg) {
          console.log(msg.errcode)
        }
      } catch (err) {
        console.log(err)
      }
    }
  }

  count = count || 0

  try {
    await user.save()
  } catch (e) {
    console.log(e)
  }

  return {
    user: user,
    count: count
  }
}
